package com.yishe.utils;


import com.yishe.config.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author : chusifeng
 * @version :v1.0
 * @date :Create in 2020/11/16 14:42
 * @description: 请求第三方接口的封装工具
 * @package com.xxl.job.medical.utils
 * @className HttpUtils
 */
@Slf4j
public class HttpUtils {

    private static final String TITLE = "请求第三方接口|";
    private static volatile RestTemplate restTemplateProxy;
    private static final Object lock = new Object();
    /**
     * 返回二进制流的请求头体配置
     */
    private static volatile HttpEntity<String> STREAMENTITY;

    public static void setRestTemplateProxy(RestTemplate restTemplate) {
        if(restTemplateProxy == null) {
            synchronized (lock) {
                if (restTemplateProxy == null) {
                    restTemplateProxy = restTemplate;
                }
            }
        }
    }
    static {
        init();
    }
    private static void init(){
        if (null == STREAMENTITY){
            synchronized (HttpUtils.class) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                STREAMENTITY = new HttpEntity<>("parameters", headers);
            }
        }
    }

    /**
     * 获取影像文件的二进制流
     * @param url
     * @return
     */
    public static ObjectRestResponse httpGetImg(String url) {
        log.info("{},请求下载影像文件，请求方式：get，请求url：{}", TITLE, url);
        ObjectRestResponse response = new ObjectRestResponse();
        Object result = null;
        try {
            ResponseEntity<byte[]> responseEntity = restTemplateProxy.exchange(url, HttpMethod.GET, STREAMENTITY, byte[].class);
            if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                result = responseEntity.getBody();
            }
            response.setData(result);
        } catch (RuntimeException e) {
            log.error("{},请求下载影像文件，请求方式：get，请求url：{},请求出错:{}", TITLE, url,  e);
            response.setErrorMsg("请求第三方接口出错");
        }
        log.info("{},请求下载影像文件，请求方式：get，请求url：{}，处理完成", TITLE, url);
        return response;
    }

    /**
     * create by: chusifeng
     * Create in 15:52
     * Description:获取请求entity
     */
    private static HttpEntity getEntity(Map params) {
        HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return new HttpEntity<>(params, headers);
    }

}
